﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace TileEditorControls
{
    /// <summary>
    /// Interaction logic for Tile.xaml
    /// </summary>
    public partial class Tile : UserControl
    {

        public static readonly RoutedEvent TileHoverEvent = EventManager.RegisterRoutedEvent(
            "TileHover", RoutingStrategy.Bubble, typeof(TileHoverRoutedEventHandler), typeof(Tile));

        private static DependencyProperty BackGroundProperty =
            DependencyProperty.Register("Background", typeof (Brush), typeof (Tile),
                                        new PropertyMetadata(Brushes.Transparent,OnBackGroundPropertyChanged));

        public Brush BackGround
        {
            get { return (Brush) GetValue(BackGroundProperty);}
            set { SetValue(BackGroundProperty, value);}
        }

        // Provide CLR accessors for the TileHoverEvent
        public event TileHoverRoutedEventHandler TileHover
        {
            add { AddHandler(TileHoverEvent, value); }
            remove { RemoveHandler(TileHoverEvent, value); }
        }

        public Tile()
        {
            InitializeComponent();
        }

        private static void OnBorderPropertyChanged (DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            Tile tile = sender as Tile;
            if ( tile != null )
            {
                tile.BorderBrush = (Brush)args.NewValue;
            }
        }

        private static void OnBackGroundPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            Tile tile = sender as Tile;
            if (tile != null)
            {
                tile.ContentPlaceHolder.Fill = (Brush)args.NewValue;
            }
        }

        // This method raises the Tap event
        private void RaiseTileHoverEvent()
        {
            if (TileHoverEvent != null)
            {

                TileHoverEventArgs newEventArgs = new TileHoverEventArgs();
                newEventArgs.RoutedEvent = Tile.TileHoverEvent;
                newEventArgs.Source = this;
                newEventArgs.xPos = Grid.GetColumn(this);
                newEventArgs.yPos = Grid.GetRow(this);
                RaiseEvent(newEventArgs);
            }
        }

        private void ContentPlaceHolder_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            RaiseTileHoverEvent();
        }

    }

    public class TileHoverEventArgs : RoutedEventArgs
    {
        public TileHoverEventArgs()
            : base()
        { }

        public int xPos { get; set; }
        public int yPos { get; set; }
    }

    public delegate void TileHoverRoutedEventHandler( object sender, TileHoverEventArgs args);
}
